<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>

<?php
$_htmlId = $block->getHtmlId() ? $block->getHtmlId() : '_' . uniqid();
$_colspan = $block->isAddAfter() ? 2 : 1;
?>

<div class="design_theme_ua_regexp" id="grid<?php /* @escapeNotVerified */ echo $_htmlId; ?>">
    <div class="admin__control-table-wrapper">
        <table class="admin__control-table">
            <thead>
            <tr>
                <?php foreach ($block->getColumns() as $columnName => $column): ?>
                    <th><?php /* @escapeNotVerified */ echo $column['label']; ?></th>
                <?php endforeach;?>
                <th class="col-actions" colspan="<?php /* @escapeNotVerified */ echo $_colspan; ?>">Action</th>
            </tr>
            </thead>
            <tfoot>
            <tr>
                <td colspan="<?php echo count($block->getColumns())+$_colspan; ?>" class="col-actions-add">
                    <button id="addToEndBtn<?php /* @escapeNotVerified */ echo $_htmlId; ?>" class="action-add" title="<?php /* @escapeNotVerified */ echo __('Add'); ?>" type="button">
                        <span><?php /* @escapeNotVerified */ echo $block->getAddButtonLabel(); ?><?php /* @escapeNotVerified */ echo __('Add'); ?></span>
                    </button>
                </td>
            </tr>
            </tfoot>
            <tbody id="addRow<?php /* @escapeNotVerified */ echo $_htmlId; ?>"></tbody>
        </table>
    </div>
    <input type="hidden" name="<?php /* @escapeNotVerified */ echo $block->getElement()->getName(); ?>[__empty]" value="" />

    <script>
        require([
            'mage/template',
            'prototype'
        ], function (mageTemplate) {
        // create row creator
        window.arrayRow<?php /* @escapeNotVerified */ echo $_htmlId ?> = {

            // define row prototypeJS template
            template: mageTemplate(
                    '<tr id="<%- _id %>">'
                    <?php foreach ($block->getColumns() as $columnName => $column): ?>
                            + '<td>'
                            + '<?php /* @escapeNotVerified */ echo $block->renderCellTemplate($columnName)?>'
                            + '<\/td>'
                        <?php endforeach; ?>

                    <?php if ($block->isAddAfter()): ?>
                            + '<td><button class="action-add" type="button" id="addAfterBtn<%- _id %>"><span><?php /* @escapeNotVerified */ echo __('Add after'); ?><\/span><\/button><\/td>'
                        <?php endif; ?>

                            + '<td class="col-actions"><button onclick="arrayRow<?php /* @escapeNotVerified */ echo $_htmlId ?>.del(\'<%- _id %>\')" class="action-delete" type="button"><span><?php /* @escapeNotVerified */ echo __('Delete'); ?><\/span><\/button><\/td>'
                            +'<\/tr>'
            ),

            add: function(rowData, insertAfterId) {
                // generate default template data
                var templateValues;

                // Prepare template values
                if (rowData) {
                    templateValues = rowData;
                } else {
                    var d = new Date();
                    templateValues = {
                <?php foreach ($block->getColumns() as $columnName => $column): ?>
                    <?php /* @escapeNotVerified */ echo $columnName ?>: '',
                        'option_extra_attrs': {},
                    <?php endforeach; ?>
                        _id: '_' + d.getTime() + '_' + d.getMilliseconds()
                };
            }

            // Insert new row after specified row or at the bottom
            if (insertAfterId) {
            Element.insert($(insertAfterId), {after: this.template(templateValues)});
        } else {
            Element.insert($('addRow<?php /* @escapeNotVerified */ echo $_htmlId ?>'), {bottom: this.template(templateValues)});
        }

        // Fill controls with data
        if (rowData) {
            var rowInputElementNames = Object.keys(rowData.column_values);
            for (var i = 0; i < rowInputElementNames.length; i++) {
                if ($(rowInputElementNames[i])) {
                    $(rowInputElementNames[i]).value = rowData.column_values[rowInputElementNames[i]];
                }
            }
        }

        // Add event for {addAfterBtn} button
        <?php if ($block->isAddAfter()): ?>
        Event.observe('addAfterBtn' + templateValues._id, 'click', this.add.bind(this, false, templateValues._id));
            <?php endif; ?>
        },

        del: function(rowId) {
            $(rowId).remove();
        }
        }

        // bind add action to "Add" button in last row
        Event.observe('addToEndBtn<?php /* @escapeNotVerified */ echo $_htmlId ?>', 'click', arrayRow<?php /* @escapeNotVerified */ echo $_htmlId ?>.add.bind(arrayRow<?php /* @escapeNotVerified */ echo $_htmlId ?>, false, false));

        // add existing rows
        <?php
        foreach ($block->getArrayRows() as $_rowId => $_row) {
            /* @escapeNotVerified */ echo "arrayRow{$_htmlId}.add(" . $_row->toJson() . ");\n";
        }
        ?>

        // Toggle the grid availability, if element is disabled (depending on scope)
        <?php if ($block->getElement()->getDisabled()):?>
        toggleValueElements({checked: true}, $('grid<?php /* @escapeNotVerified */ echo $_htmlId; ?>').parentNode);
            <?php endif;?>
        });
    </script>
</div>
